<template>
  <div>
    <div class="headButton">
      <span class="title">{{'项目反馈-'}}<a @click.prevent="goBack" class="back-class" href="#">项目详情</a></span>
      <el-radio-group v-model="tabPosition" @change="queryChange">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="create">由我创建</el-radio-button>
        <el-radio-button label="accept">指派给我</el-radio-button>
        <el-radio-button label="complete">由我解决</el-radio-button>
        <el-radio-button label="unaccept">未指派</el-radio-button>
<!--        <el-radio-button label="batchUpdatastatus" @click.native.prevent="queryChange('batchUpdatastatus')">批量待客户验收</el-radio-button>-->
      </el-radio-group>
      <vxe-button style="margin-left:10px" status="success"  size="small" transfer>
        <template #default>批量解决</template>
        <template #dropdowns>
          <vxe-button type="text" v-for="(it, index) in btnsList" @click.native.prevent="queryChange('batchUpdatastatus', it.DictId)" :key="index">{{it.DictName}}</vxe-button>
        </template>
      </vxe-button>
      <el-button style="margin-left:10px" type="success" icon="el-icon-circle-plus-outline" size="small"
                 @click="add">提反馈
      </el-button>
<!--      <vxe-button @click="batchUpdatastatus">批量待客户验收</vxe-button>-->
    </div>
    <search-component :colum="colum" :formValue="formValue" class="search" @exportBtn="exportBtn" :isShowExport="true"
                      @search="search" @reset="reset" ref="search">
    </search-component>
    <div style="display: flex; justify-content: flex-end">
      <el-dropdown :hide-on-click="false" trigger="click" class="ycDataTableDropdown">
        <el-button @click="showColumnsClick" size="small" class="ycMoreCss"><i class="el-icon-more"></i></el-button>
        <el-dropdown-menu slot="dropdown">
          <template v-for="(column, index) in columns1">
            <el-dropdown-item  :key="index">
              <el-checkbox v-model="column.visible" @change="showColumnsChange" :disabled="column.title === '反馈标题'">{{column.title}}</el-checkbox>
            </el-dropdown-item>
          </template>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div style="position: relative">
      <vxe-grid
          ref="xTable3"
          border
          context-menu
          highlight-hover-row
          :scroll-y="{gt: -1}"
          resizable
          :data="tableData"
          :loading="loading"
          :pager-config="pagerConfig"
          @checkbox-change="checkboxChangeEvent"
          @checkbox-all="checkboxChangeEvent"
          @page-change="pageChangeChange">
        <vxe-table-column type="checkbox" width="40"></vxe-table-column>
        <vxe-table-column field="Id" title="编号" :width="'160px'" sortable></vxe-table-column>
        <vxe-table-column field="Taskid" title="任务编号" :min-width="'160px'" sortable>
          <template v-slot="{ row }">
            <a class="link-name" @click.prevent="editDetil1(row)" :href="linkName1(row)"><span>{{row.Taskid === '0' ? '' : row.Taskid}}</span></a>
          </template>
        </vxe-table-column>
        <vxe-table-column field="Modulename" title="模块" :width="'120px'" sortable></vxe-table-column>
        <vxe-table-column field="Level" title="级别" align="center" :width="'72px'" sortable>
          <template v-slot="{ row }">
            <el-tag :type="tagType[row.Level-1]">
              {{ statusFilterOptions(row.Level, 'LEVEL') }}
            </el-tag>
          </template>
        </vxe-table-column>
        <vxe-table-column field="Name" title="反馈标题" :min-width="'250px'" sortable>
          <template v-slot="{ row }">
            <a class="link-name" @click.prevent="editDetil(row)" :href="linkName(row)"><span>{{row.Name}}</span></a>
          </template>
        </vxe-table-column>
        <vxe-table-column field="Type" title="分类" align="center" :width="'85px'" sortable>
          <template v-slot="{ row }">
            <span>{{ statusFilterOptions(row.Type, 'TEST_TYPE') }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="Versionno" title="版本号" width="85" sortable ></vxe-table-column>
        <vxe-table-column field="Status" title="状态" align="center" :width="'110px'" sortable>
          <template v-slot="{ row }">
            <span>{{ statusFilterOptions(row.Status, 'TEST_STATUS') }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="Acceptevn" title="验收环境" align="center" :width="'110px'" sortable>
          <template v-slot="{ row }">
            <span>{{ getCode(row.Acceptevn, 'TEST_YSHJ') }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="Userrealname" title="创建人" width="100" sortable></vxe-table-column>
        <vxe-table-column field="Departname" title="部门" width="100" sortable></vxe-table-column>
        <vxe-table-column field="Uatdepartname" title="验收部门" width="100" sortable></vxe-table-column>
        <vxe-table-column field="Created" title="创建日期" :formatter="formatDate" width="100" sortable ></vxe-table-column>
        <vxe-table-column field="Acceptrealname" title="指派人" width="85" sortable></vxe-table-column>
        <vxe-table-column field="Completerealname" title="解决人" width="85" sortable></vxe-table-column>
        <vxe-table-column field="Completed" title="解决日期" :formatter="formatDate" width="100" sortable></vxe-table-column>
        <vxe-table-column field="Changed" title="最后更新日期" :formatter="formatDate" width="150" sortable ></vxe-table-column>
        <vxe-table-column field="Opear" title="操作" width="100px" align="center" fixed="right">
          <template v-slot="{ row }">
            <vxe-button type="text" circle icon="el-icon-thumb" @click="assigned(row)" size="small" title="指派"></vxe-button>
<!--            <vxe-button type="text" circle icon="el-icon-s-tools" @click="createTaskBtn(row)" size="small" title="新建任务"></vxe-button>-->
            <vxe-button type="text" circle icon="el-icon-edit-outline" size="small" @click="edit(row)" v-if="$store.getters.userId === row.Userid" title="编辑"></vxe-button>
          </template>
        </vxe-table-column>
      </vxe-grid>
    </div>
    <TestAssigned :visible.sync="modalVisible" title="反馈指派" :formData="formData" @search="search"></TestAssigned>
    <TestDetail :visible.sync="editVisible" title="反馈管理" :formData="editData" @saveClose="search"></TestDetail>
    <TestAdd :visible.sync="addVisible" title="反馈管理" :formData="addData" :editModel="editModel"></TestAdd>
    <create-task :visible.sync="createTaskVisible" :formDataP="createData"></create-task>
  </div>
</template>

<script>
  import searchComponent from "@/components/element/layoutComponents/searchFrom/searchComponent.vue";
  import DictionarySelect from "@/components/element/select/DictionarySelect";
  import SelectProjectModule from "@/components/element/select/SelectProjectModule";
  import SelectProjectTeam from "@/components/element/select/SelectProjectTeam";
  import SelectDepart from "@/components/element/select/SelectDepart";
  import projectTestApi from "@/api/projectTestApi";
  import TestAssigned from "./TestAssigned";
  import TestDetail from "./TestDetail";
  import TestAdd from "./TestAdd";
  import {mapGetters} from "vuex";
  import { formatDateString } from '@/utils/date'
  import { downFile } from '@/api/downloadApi.js'
  import createTask from "@/page/ProjectManage/modules/testModule/createTask";

  export default {
    name: 'ProjectManageTest',
    components: {
      searchComponent,
      TestAssigned,
      TestDetail,
      TestAdd,
      createTask,
      SelectProjectTeam
    },
    mounted() {
      let a = ''
      if (this.$router.currentRoute.params.pid) {
        this.$set(this.formValue, 'testno', this.$router.currentRoute.params.pid)
        a = '1'
      }
      this.getLists()
      this.search(a)
      this.$nextTick(() => {
        if (this.$refs.xTable3) {
          this.columns = this.$refs.xTable3.getColumns()
          this.columns.forEach(it => {
            if (it.property === 'Versionno' || it.property === 'Changed'
                || it.property === 'Acceptevn' || it.property === 'Taskid') {
              it.visible = false
            }
          })
          this.$refs.xTable3.refreshColumn()
        }
      })
    },
    // activated() {
    //   let a = ''
    //   if (this.$router.currentRoute.params.pid) {
    //     this.$set(this.formValue, 'testno', this.$router.currentRoute.params.pid)
    //     a = '1'
    //   }
    //   this.search(a)
    // },
    computed: {
      ...mapGetters(['dictionary']),
      statusList() {
        return (DictTypeCode) => {
          return this.dictionary.filter(item => item.DictTypeCode === DictTypeCode)
        }
      },
      statusFilterOptions() {
        return (cellValue, DictTypeCode) => {
          let filter = this.statusList(DictTypeCode).filter(it => it.DictId === cellValue.toString())
          if (filter.length > 0) {
            return filter[0].DictName
          }
          return ''
        }
      },
      linkName () {
        return (row) => {
          let hp = window.location.protocol
          let host = window.location.host
          return `${hp}//${host}/view/test/show/${row.Id}`
        }
      },
      linkName1 () {
        return (row) => {
          let hp = window.location.protocol
          let host = window.location.host
          return `${hp}//${host}/view/taskEdit/${row.Taskid}`
        }
      },
    },
    activated() {
      if (this.tabPosition !== this.$router.currentRoute.query.type) {
        let type = this.$router.currentRoute.query.type
        this.tabPosition = type
        this.queryChange(type)
      }
    },
    data() {
      return {
        showVisibleColumn: false,
        columns: [],
        columns1: [],
        createData: {},
        createTaskVisible: false,
        btnsList: [],
        selectRecords: [],
        loading: false,
        tagType: ['danger', 'warning', 'info', 'success'],
        fullscreenLoading: false,
        editModel: 'C',
        formData: {},
        modalVisible: false,
        editData: {},
        editVisible: false,
        addData: {},
        addVisible: false,
        tabPosition: '',
        formValue: {
          p: 1,
          pageoffset: 15
        },
        colum: [
          {
            placeholder: '请选择状态',
            prop: 'status',
            size: 'small',
            dictTypeCode: 'TEST_STATUS',
            componentName: DictionarySelect,
            value: 'status',
            clearable: true,
            show: true,
            multiple: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择分类',
            prop: 'type',
            size: 'small',
            dictTypeCode: 'TEST_TYPE',
            componentName: DictionarySelect,
            value: 'type',
            clearable: true,
            show: true,
            multiple: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择指派人',
            selectTitle: '指派人',
            prop: 'acceptid',
            size: 'small',
            componentName: SelectProjectTeam,
            value: 'acceptid',
            ref: 'acceptid',
            clearable: true,
            show: true,
            attrs: {
              multiple: true,
              column: [
                { field: 'Userrealname' }
              ],
              showValueShow: []
            },
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择模块',
            prop: 'moduleid',
            size: 'small',
            componentName: SelectProjectModule,
            data: 'URL',
            value: 'moduleid',
            ref: 'moduleid',
            clearable: true,
            show: true,
            attrs: {
              multiple: true,
              column: [
                { field: 'Name', title: '模块名称' }
              ],
            },
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择反馈环境',
            prop: 'env',
            size: 'small',
            dictTypeCode: 'ENV',
            componentName: DictionarySelect,
            value: 'env',
            clearable: true,
            show: true,
            multiple: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择创建人',
            selectTitle: '创建人',
            prop: 'creatId',
            size: 'small',
            componentName: SelectProjectTeam,
            value: 'creatId',
            ref: 'creatId',
            clearable: true,
            show: true,
            attrs: {
              multiple: true,
              showValueShow: [],
              column: [
                { field: 'Userrealname' }
              ]
            },
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '创建人部门',
            selectTitle: '创建人部门',
            prop: 'departid',
            size: 'small',
            componentName: SelectDepart,
            value: 'departid',
            ref: 'departid',
            clearable: true,
            show: true,
            attrs: {
              multiple: true
            },
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择创建开始时间',
            prop: 'createStarted',
            size: 'small',
            componentName: 'el-date-picker',
            value: 'createStarted',
            clearable: true,
            show: true,
            multiple: true,
            attrs: {
              'value-format': 'timestamp'
            },
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择创建结束时间',
            prop: 'createEnd',
            size: 'small',
            componentName: 'el-date-picker',
            value: 'createEnd',
            clearable: true,
            show: true,
            multiple: true,
            attrs: {
              'value-format': 'timestamp'
            },
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请输入标题、内容、编号',
            prop: 'keywords',
            size: 'small',
            componentName: 'vxe-input',
            type: 'integer',
            min: 0,
            value: 'keywords',
            clearable: true,
            show: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          // {
          //   placeholder: '请输入开始估算工时',
          //   prop: 'estimatedtasktimestart',
          //   size: 'small',
          //   componentName: 'vxe-input',
          //   attrs: {
          //     type: 'number',
          //     min: 0,
          //     step: 0.1
          //   },
          //   value: 'estimatedtasktimestart',
          //   clearable: true,
          //   show: true,
          //   elcolStyle: {
          //     'width': '200px'
          //   }
          // },
          // {
          //   placeholder: '请输入结束估算工时',
          //   prop: 'estimatedtasktimestartend',
          //   size: 'small',
          //   componentName: 'vxe-input',
          //   attrs: {
          //     type: 'number',
          //     min: 0,
          //     step: 0.1
          //   },
          //   value: 'estimatedtasktimestartend',
          //   clearable: true,
          //   show: true,
          //   elcolStyle: {
          //     'width': '200px'
          //   }
          // },
          // {
          //   placeholder: '请选择客户确认状态',
          //   prop: 'bussconfirmstatus',
          //   size: 'small',
          //   dictTypeCode: 'BUSSCONFIRM_STATUS',
          //   componentName: DictionarySelect,
          //   value: 'bussconfirmstatus',
          //   clearable: true,
          //   show: true,
          //   multiple: true,
          //   elcolStyle: {
          //     'width': '200px'
          //   }
          // },
          {
            placeholder: '请输入反馈编号',
            prop: 'testno',
            size: 'small',
            componentName: 'vxe-input',
            value: 'testno',
            clearable: true,
            show: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择验收部门',
            prop: 'uatdepart',
            size: 'small',
            multiple: true,
            componentName: SelectDepart,
            value: 'uatdepart',
            clearable: true,
            show: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请输入版本号或者分支',
            prop: 'vesionno',
            size: 'small',
            componentName: 'vxe-input',
            value: 'vesionno',
            clearable: true,
            show: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择级别',
            prop: 'level',
            size: 'small',
            dictTypeCode: 'LEVEL',
            componentName: DictionarySelect,
            value: 'level',
            clearable: true,
            show: true,
            multiple: true,
            elcolStyle: {
              'width': '200px'
            }
          },
          {
            placeholder: '请选择验收环境',
            prop: 'acceptevn',
            size: 'small',
            dictTypeCode: 'TEST_YSHJ',
            componentName: DictionarySelect,
            value: 'acceptevn',
            clearable: true,
            show: true,
            multiple: true,
            elcolStyle: {
              'width': '200px'
            }
          }
        ],
        tableData: [],
        // toolbar: {
        //   slots: {
        //     buttons: 'toolbar-buttons'
        //   },
        // },
        pagerConfig: {
          currentPage: 1,
          pageSize: 15,
          total: 0,
          pagerCount: 7,
          pageSizes: [10, 15, 20, 50, 100]
        }
      }
    },
    methods: {
      showColumnsChange () {
        this.$refs.xTable3.refreshColumn()
      },
      showColumnsClick () {

        this.columns1 = this.columns.slice(1)
        this.showVisibleColumn = !this.showVisibleColumn
      },
      createTaskBtn (row) {
        this.createData = row
        this.createTaskVisible = true
      },
      getLists() {
        this.$store.dispatch('GetDictItems', 'TEST_STATUS').then(res => {
          res.sort((a, b) => a.sortNo - b.sortNo)
          console.log(this.btnsList)
          this.btnsList = res
        })
        // this.$store.dispatch('GetDictItems', 'TEST_STATUS').then(res => {
        //   res.sort((a, b) => a.sortNo - b.sortNo)
        //   $this.optionValues = res
        //   $this.getTipTxtValueArea(res)
        //   this.getSelectChange(res)
        // })
      },
      // 选择
      checkboxChangeEvent ({ records }) {
        this.selectRecords = records
      },
      // 返回项目详情
      goBack () {
        this.$router.push(`/view/project/details/${this.$route.params.id}`)
      },
      // 导出
      exportBtn () {
        this.fullscreenLoading = this.$loading({
          lock: true,
          text: '下载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let id = this.$route.params.id
        let a = JSON.parse(JSON.stringify(this.formValue))
        a.id = this.$route.params.id
        if (a.createStarted) {
          a.createStarted = a.createStarted / 1000
        }
        if (a.createEnd) {
          a.createEnd = a.createEnd / 1000
        }
        if (a.createStarted && a.createEnd && a.createStarted === a.createEnd) {
          a.createEnd = a.createEnd + (60 * 60 * 24)
        }
        projectTestApi.getExport(a).then(res => {
          downFile(res)
        }).finally(_ => {
          this.fullscreenLoading.close()
        })
      },
      editDetil (row) {
        // this.editData = JSON.parse(JSON.stringify(row))
        // this.editVisible = true
        this.$router.push(`/view/test/show/${row.Id}`)
      },
      editDetil1 (row) {
        // this.editData = JSON.parse(JSON.stringify(row))
        // this.editVisible = true
        this.$router.push(`/view/taskEdit/${row.Taskid}`)
      },
      edit(row) {
        // this.$router.push(`/view/project/testadd/${row.Id}`)
        this.addData = JSON.parse(JSON.stringify(row))
        this.editModel = 'E'
        this.addVisible = true
      },
      add() {
        // this.$router.push(`/view/project/testadd`)
        this.editModel = 'C'
        this.addData = {
          Moduleid: '',
          acceptid: '',
          Type:'',
          Name:'',
          Level:'',
          Desc:'',
          Os:'',
          Browser:'',
          Bussconfirmstatus:'',
          Env:'',
          Attachment:''
        }
        this.addVisible = true
      },
      assigned(row) {
        this.formData = {
          acceptid: '',
          Id: row.Id,
          note: ''
        }
        this.modalVisible = true
      },
      queryChange(val, status) {
        this.$set(this.formValue, 'creatId', undefined)
        this.$set(this.formValue, 'acceptid', undefined)
        if (val === 'batchUpdatastatus') {
          if (this.selectRecords.length > 0) {
            let a = {
              Taskid: this.selectRecords.map(it => it.Id),
              Status: Number(status)
            }
            projectTestApi.BatchUpdateStatus(a).then(res => {
              this.$message({ type: res.code === 1 ? 'success' : 'warning', message: res.message })
              if (res.code === 1) {
                this.search()
              }
            }).catch(() => this.$message.error('批量设置失败')).finally(() => this.loading = false);
          } else {
            return this.$message.error('请先选择数据')
          }
        } else {
          const query=JSON.parse(JSON.stringify(this.$router.currentRoute.query))
          query.type = val
          this.$router.push({ path: this.$route.path, query })
          this.$set(this.formValue, 'filter', val)
          if (val === 'create') {
            this.$set(this.formValue, 'creatId', [this.$store.state.user.id])
          } else if (val === 'accept') {
            // 指派人
            this.$set(this.formValue, 'acceptid', [this.$store.state.user.id])
          }
          this.search()
        }
      },
      search(a) {
        if (this.$route.params.id) {
          this.tableData = []
          let query1 = Object.assign({id: this.$route.params.id}, this.formValue)
          let query = JSON.parse(JSON.stringify(query1))
          if (query.createStarted) {
            query.createStarted = query.createStarted / 1000
          }
          if (query.createEnd) {
            query.createEnd = query.createEnd / 1000
          }
          if (query.createStarted && query.createEnd && query.createStarted === query.createEnd) {
            query.createEnd = query.createEnd + (60 * 60 * 24)
          }
          this.loading = true
          projectTestApi.getPage(query).then(res => {
            this.selectRecords = []
            if (res && res.Tests) {
              this.tableData = res.Tests;
              this.pagerConfigFun(res)
              if (this.$router.currentRoute.params.pid && a === '1') {
                if (this.tableData.length > 0) {
                  this.editDetil(this.tableData[0])
                }
              }
            } else if (null === res.Tests) {
              this.tableData = []
              this.pagerConfigFun(res)
            } else {
              this.$message.error(res.message);
            }
          }).catch(() => this.$message.error('获取反馈信息失败')).finally(() => this.loading = false);
        }
      },
      reset() {
        this.formValue = {
          p: 1,
          pageoffset: 15
        }
      },
      pagerConfigFun(res) {
        this.pagerConfig.currentPage = res.Page
        this.formValue.p = this.pagerConfig.currentPage
        this.pagerConfig.total = res.Total
      },
      pageChangeChange(pageConfig) {
        this.formValue.p = pageConfig.currentPage
        this.pagerConfig.currentPage = pageConfig.currentPage
        this.formValue.pageoffset = pageConfig.pageSize
        this.pagerConfig.pageSize = pageConfig.pageSize
        this.search()
      },
      formatDate ({ cellValue }) {
        let a = formatDateString(cellValue * 1000, 'yyyy-MM-dd hh:mm:ss')
        if (a.indexOf('1970-01-01') >= 0 ) {
          return ''
        }
        return a
      }
    }
  }
</script>
<style>
.back-class {
  color: #00d1b2;
}
  .headButton {
    text-align: right;
    padding-bottom: 10px;
  }

  .headButton .title {
    float: left;
    font-width: normal;
    font-size: 20px;
  }

  .link-name {
    color: #65CEA7;
  }

  .link-name:hover {
    color: #353F4F;
    cursor: pointer;
  }
</style>
